package com.it00zyq.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it00zyq.admin.param.LoginParam;
import com.it00zyq.admin.param.RegisterParam;
import com.it00zyq.admin.result.LoginResult;
import com.it00zyq.admin.service.UserService;
import com.it00zyq.common.entity.User;
import com.it00zyq.common.mapper.UserMapper;
import com.it00zyq.common.utils.ApiException;
import com.it00zyq.common.enums.ErrorEnum;
import com.it00zyq.common.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @Author zyq
 * @Date 2022/4/25 16:52
 * @Description TODO
 * @Version 1.0
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    private final JwtUtil jwtUtil;
    private final static BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    public LoginResult login(LoginParam param) {
        // 根据用户名查询用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", param.getUsername());
        User user = userMapper.selectOne(wrapper);

        // 用户判空 密码校验
        if (ObjectUtils.isEmpty(user) || !encoder.matches(param.getPassword(), user.getPassword())) {
            throw new ApiException(ErrorEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        // 返回用户信息和令牌
        LoginResult result = new LoginResult();
        BeanUtils.copyProperties(user, result);
        result.setToken(jwtUtil.getToken(user.getUsername()));
        return result;
    }

    @Override
    public void register(RegisterParam param) {
        // 判断用户名是否已存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", param.getUsername());
        User user = userMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(user)) {
            throw new ApiException("用户名已存在");
        }

        // 保存到数据库
        User registerUser = new User();
        BeanUtils.copyProperties(param, registerUser);
        registerUser.setPassword(encoder.encode(param.getPassword()));
        userMapper.insert(registerUser);
    }

}
